#include "user.h"

void usart_sendstr(USART_TypeDef * USATRX , char * str,int size)
{
    int i = 0;
    USART_ClearFlag(USATRX,USART_FLAG_TC);
    for(i=0;i<size;i++)
    {
        USART_SendData(USATRX,*str);
        while(RESET == USART_GetFlagStatus(USATRX,USART_FLAG_TC));
        USART_ClearFlag(USATRX,USART_FLAG_TC);
        str++;
    }
}

void ESP8266_Config()
{	
  usart_sendstr(USART2,"AT+RESTORE\r\n",strlen("AT+RESTORE\r\n"));
  delay_ms(3000);
  usart_sendstr(USART2,"AT\r\n",sizeof("AT\r\n"));
  delay_ms(3000);
	usart_sendstr(USART2,"AT+CWMODE=1\r\n",sizeof("AT+CWMODE=1\r\n"));
  delay_ms(3000);
	usart_sendstr(USART2,"AT+CWJAP=\"yxx\",\"12345678\"\r\n",sizeof("AT+CWJAP=\"yxx\",\"12345678\"\r\n"));
	delay_ms(3000);
	usart_sendstr(USART2,"AT+CIPMUX=0\r\n",sizeof( "AT+CIPMUX=0\r\n"));
  delay_ms(3000);
	usart_sendstr(USART2,"AT+CIPSTART=\"TCP\",\"192.168.50.170\",8080\r\n",sizeof("AT+CIPSTART=0,\"TCP\",\"192.168.50.170\",8081\r\n"));
  delay_ms(3000);

}

void Delay_TIM6_us(u16 delay)
{
	
	  TIM_Cmd(TIM6,ENABLE); 
    while(TIM6->CNT < delay);
    TIM6->CNT = 0;
    TIM_Cmd(TIM6,DISABLE);
}
void Delay_TIM6_ms(u16 delay)
{
    int i;
    for(i=0;i<delay;i++)
    {
        Delay_TIM6_us(1000);
    }
}

void Send_U8_Data(USART_TypeDef * USATRX , u8 * str,int size)
{
    int i = 0;
    USART_ClearFlag(USATRX,USART_FLAG_TC);
    for(i=0;i<size;i++)
    {
        USART_SendData(USATRX,*str);
        while(RESET == USART_GetFlagStatus(USATRX,USART_FLAG_TC));
        USART_ClearFlag(USATRX,USART_FLAG_TC);
        str++;
    }
}

int Send_Data_server(u8 *data,u8 data_len)
{
  u8 str[128] = "";
	int userID = 101;//??ID
  u8 CheckSum = 0x00;
  str[0]=0x5a;
	str[1]=0x23;//??
  str[2]=userID;//???????+??ID=8
  str[3] = userID;
	str[4] = data_len;
  for(int i=0;i<data_len;i++)
	{
        str[i+5]=data[i];
        CheckSum+=data[i];
    }
  str[data_len+5]=CheckSum;
  usart_sendstr(USART2,"AT+CIPSEND=15\r\n",sizeof( "AT+CIPSEND=15\r\n"));
	delay_ms(5);
	Send_U8_Data(USART2,str,15);
	delay_ms(5);
	memset(str,0,sizeof(str));
    return 0;
}
